/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.snow.spring.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * @author icanci
 * @date Created in 2021/05/19 16:50
 * @version 1.0
 */
@Slf4j
public class ClassUtil {
    private static final String FILE_PROTOCOL = "file";
    private static final String END_CLASS     = ".class";

    /**
     * 获取包下的类集合
     * @param packageName 包名
     * @return 返回类集合
     */
    public static Set<Class<?>> extractPackageClass(String packageName) {
        // 获取类加载器
        ClassLoader classLoader = getClassLoader();
        // 通过类加载器获取加载的资源信息
        URL url = classLoader.getResource(packageName.replace(".", "/"));
        if (null == url) {
            log.warn("unable to retrieve anything from package:{}", packageName);
            return null;
        }
        // 依据不同的资源类型，采用不同的方式获取资源的集合
        Set<Class<?>> classSet = null;
        // 过滤出文件类型的资源
        if (url.getProtocol().equalsIgnoreCase(FILE_PROTOCOL)) {
            classSet = new HashSet<>();
            File packageDirectory = new File(url.getPath());
            extractClassFile(classSet, packageDirectory, packageName);
        }
        // TODO 此处可以加入针对其他方式的class文件的处理 如 jar、zip等
        return classSet;
    }

    /**
     * 获取目标 package 里面的所有class文件（包括子package里面的class文件）
     * @param emptyClassSet 装载目标类的集合
     * @param fileSource 文件或者目录
     * @param packageName 包名
     */
    private static void extractClassFile(Set<Class<?>> emptyClassSet, File fileSource, String packageName) {
        if (!fileSource.isDirectory()) {
            return;
        }
        // 如果是一个文件夹，调用当前文件夹的文件或者文件夹
        File[] files = fileSource.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    return true;
                } else {
                    // 获取文件的绝对子路径
                    String absolutePath = file.getAbsolutePath();
                    if (absolutePath.endsWith(END_CLASS)) {
                        // 直接加载
                        addToClassSet(absolutePath);
                    }
                }
                return false;
            }

            /**
             * 根据 class 文件的绝对值路径，获取并生成class对象，并放入classSet中去
             * @param absolutePath
             */
            private void addToClassSet(String absolutePath) {
                // 从class文件的绝对值路径提取出包含package的类名
                absolutePath = absolutePath.replace(File.separator, ".");
                String className = absolutePath.substring(absolutePath.indexOf(packageName));
                className = className.substring(0, className.lastIndexOf("."));
                // 通过反射创建对应的class对象放到classSet中去
                Class<?> clazz = loadClass(className);
                emptyClassSet.add(clazz);
            }

            /**
             * 返回 Class 实例
             * @param className class 全路径
             * @return 返回class对象
             */
            private Class<?> loadClass(String className) {
                try {
                    return Class.forName(className);
                } catch (ClassNotFoundException e) {
                    log.error("load class error:{}", e, e.getStackTrace());
                    throw new RuntimeException();
                }
            }
        });
        if (null != files) {
            for (File file : files) {
                extractClassFile(emptyClassSet, file, packageName);
            }
        }
    }

    /**
     * 获取ClassLoader对象，返回实例
     * @return ClassLoader 实例
     */
    private static ClassLoader getClassLoader() {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        log.info("the Thread Class Loader is {}", contextClassLoader);
        return contextClassLoader;
    }

    /**
     * 设置类的属性值
     *
     * @param field 成员变量
     * @param target 类实例
     * @param value 成员变量的值
     * @param accessible 是否允许设置私有属性
     */
    public static void setField(Field field, Object target, Object value, boolean accessible) {
        try {
            field.setAccessible(accessible);
            field.set(target, value);
        } catch (IllegalAccessException e) {
            log.error("setField error:{}", e, e.getStackTrace());
            throw new RuntimeException();
        }
    }

    /**
     * 实例化 Class
     * @param <T>  范型
     * @param accessible 是否私有
     * @param clazz 传入的class对象
     */
    public static <T> T newInstance(Class<?> clazz, boolean accessible) {
        try {
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(accessible);
            return (T) constructor.newInstance();
        } catch (Exception e) {
            log.error("new instance error:{}", e, e.getStackTrace());
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
